package com.linan.docmanage.controller;

import com.linan.docmanage.domain.User;
import com.linan.util.AjaxResult;
import com.linan.util.FastFdsUtil;
import org.csource.common.MyException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

@RestController
@RequestMapping("/common")
public class CommonController {

    @PostMapping("/upload-file")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file) throws IOException, MyException {
        byte[] bytes = file.getBytes();
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.split("\\.")[1];
        String[] strings = FastFdsUtil.uploadFile(bytes, extName);
        for (String string :
                strings
        ) {
            System.out.println(string);
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("groupId", strings[0]);
        map.put("docId", strings[1]);
        return new AjaxResult(map);
    }

    @PostMapping("/login")
    public AjaxResult login(@RequestBody User user, HttpServletResponse response) {
        String username = user.getUsername();
        Cookie cookie = new Cookie("username", username);
        cookie.setPath("/");
        cookie.setMaxAge(20 * 60);
        response.addCookie(cookie);
        return new AjaxResult("登录成功");

    }

    @GetMapping("/test-connect")
    public  AjaxResult testConnect (){
        return new AjaxResult();
    }
}
